// 模拟收藏路线数据
const favoriteRoutes = [
    {
        id: 1,
        title: "鼓浪屿文化之旅",
        type: "cultural",
        duration: "一天",
        difficulty: "简单",
        rating: 4.8,
        spots: ["日光岩", "菽庄花园", "钢琴博物馆", "皓月园", "郑成功纪念馆"],
        description: "探索鼓浪屿的历史文化，感受音乐之岛的独特魅力",
        collectTime: "2023-12-01",
        estimatedCost: "150-200元",
        bestTime: "全年适宜",
        tips: "建议早上出发，避开人流高峰"
    },
    {
        id: 2,
        title: "厦门大学校园游",
        type: "cultural",
        duration: "半天",
        difficulty: "简单",
        rating: 4.6,
        spots: ["芙蓉湖", "情人谷", "建南大礼堂", "嘉庚楼群", "白城沙滩"],
        description: "漫步中国最美大学校园，感受学术氛围",
        collectTime: "2023-11-28",
        estimatedCost: "免费",
        bestTime: "春秋季节",
        tips: "需要预约入校，携带身份证"
    },
    {
        id: 3,
        title: "环岛路海景骑行",
        type: "natural",
        duration: "半天",
        difficulty: "中等",
        rating: 4.7,
        spots: ["白城沙滩", "胡里山炮台", "曾厝垵", "黄厝海滩", "椰风寨"],
        description: "沿着美丽的环岛路骑行，享受海风和阳光",
        collectTime: "2023-11-25",
        estimatedCost: "50-100元",
        bestTime: "春秋季节",
        tips: "注意防晒，准备充足的水"
    },
    {
        id: 4,
        title: "中山路美食探索",
        type: "food",
        duration: "一天",
        difficulty: "简单",
        rating: 4.9,
        spots: ["中山路步行街", "局口街", "大同路", "开元路", "思明南路"],
        description: "品尝地道闽南美食，体验厦门夜市文化",
        collectTime: "2023-11-20",
        estimatedCost: "100-300元",
        bestTime: "全年适宜",
        tips: "晚上更热闹，注意饮食卫生"
    },
    {
        id: 5,
        title: "集美学村文化游",
        type: "cultural",
        duration: "一天",
        difficulty: "简单",
        rating: 4.5,
        spots: ["嘉庚公园", "集美学校", "龙舟池", "陈嘉庚纪念馆", "鳌园"],
        description: "了解华侨文化，欣赏中西合璧建筑",
        collectTime: "2023-11-15",
        estimatedCost: "80-150元",
        bestTime: "全年适宜",
        tips: "可乘坐BRT前往，交通便利"
    }
];

let currentRoutes = [...favoriteRoutes];
let selectedRoute = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadFavoriteRoutes();
    initializePage();
    renderRoutes();
    setupEventListeners();
});

function loadFavoriteRoutes() {
    // 从本地存储加载收藏路线
    const savedRoutes = localStorage.getItem('favoriteRoutes');
    if (savedRoutes) {
        try {
            const parsedRoutes = JSON.parse(savedRoutes);
            // 合并本地存储的路线和默认路线
            favoriteRoutes.splice(0, 0, ...parsedRoutes);
            currentRoutes = [...favoriteRoutes];
        } catch (error) {
            console.error('加载收藏路线失败:', error);
        }
    }
}

function initializePage() {
    // 更新统计数据
    updateStats();
    
    // 添加动态效果
    addDynamicEffects();
}

function updateStats() {
    const totalRoutes = currentRoutes.length;
    const totalDays = currentRoutes.reduce((sum, route) => {
        const days = route.duration.includes('天') ? parseInt(route.duration) : 0.5;
        return sum + days;
    }, 0);
    const totalSpots = currentRoutes.reduce((sum, route) => sum + route.spots.length, 0);
    
    document.getElementById('totalRoutes').textContent = totalRoutes;
    document.getElementById('totalDays').textContent = Math.ceil(totalDays);
    document.getElementById('totalSpots').textContent = totalSpots;
}

function addDynamicEffects() {
    // 添加数据流动效果
    setInterval(() => {
        const particles = document.querySelector('.floating-particles');
        if (particles) {
            particles.style.transform = `translateY(${Math.sin(Date.now() * 0.001) * 10}px)`;
        }
    }, 100);
    
    // 添加标题光效
    setInterval(() => {
        const titleGlow = document.querySelector('.title-glow');
        if (titleGlow) {
            titleGlow.style.opacity = Math.sin(Date.now() * 0.003) * 0.3 + 0.1;
        }
    }, 50);
}

function setupEventListeners() {
    // 筛选器事件
    document.getElementById('typeFilter').addEventListener('change', filterRoutes);
    document.getElementById('durationFilter').addEventListener('change', filterRoutes);
    document.getElementById('sortFilter').addEventListener('change', sortRoutes);
    
    // 弹窗关闭事件
    window.onclick = function(event) {
        const modal = document.getElementById('routeModal');
        if (event.target === modal) {
            closeRouteModal();
        }
    }
}

function renderRoutes() {
    const grid = document.getElementById('routesGrid');
    
    if (currentRoutes.length === 0) {
        grid.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">🗺️</div>
                <div class="empty-message">暂无收藏路线</div>
                <div class="empty-suggestion">去探索页面发现更多精彩路线吧！</div>
            </div>
        `;
        return;
    }
    
    grid.innerHTML = currentRoutes.map(route => `
        <div class="route-card" onclick="viewRouteDetails(${route.id})">
            <div class="route-header">
                <div>
                    <h3 class="route-title">${route.title}</h3>
                    <div class="route-type ${getTypeClass(route.type)}">${getTypeLabel(route.type)}</div>
                </div>
                <div class="route-rating">
                    <span style="color: #ffeb3b;">⭐</span>
                    <span style="color: #fff; font-weight: bold;">${route.rating}</span>
                </div>
            </div>
            
            <div class="route-info">
                <div class="info-item">
                    <span class="info-icon">⏰</span>
                    <span>${route.duration}</span>
                </div>
                <div class="info-item">
                    <span class="info-icon">🎯</span>
                    <span>${route.difficulty}</span>
                </div>
                <div class="info-item">
                    <span class="info-icon">💰</span>
                    <span>${route.estimatedCost}</span>
                </div>
                <div class="info-item">
                    <span class="info-icon">📅</span>
                    <span>${route.collectTime}</span>
                </div>
            </div>
            
            <div class="route-spots">
                <div class="spots-title">📍 包含景点</div>
                <div class="spots-list">
                    ${route.spots.slice(0, 4).map(spot => `<span class="spot-tag">${spot}</span>`).join('')}
                    ${route.spots.length > 4 ? `<span class="spot-tag">+${route.spots.length - 4}个</span>` : ''}
                </div>
            </div>
            
            <div class="route-actions">
                <button class="action-btn btn-view" onclick="event.stopPropagation(); viewRouteDetails(${route.id})">
                    <span>👁️</span>
                    <span>查看详情</span>
                </button>
                <button class="action-btn btn-remove" onclick="event.stopPropagation(); removeRoute(${route.id})">
                    <span>🗑️</span>
                    <span>取消收藏</span>
                </button>
            </div>
        </div>
    `).join('');
}

function getTypeClass(type) {
    const classes = {
        'cultural': 'type-cultural',
        'natural': 'type-natural',
        'food': 'type-food',
        'leisure': 'type-leisure'
    };
    return classes[type] || '';
}

function getTypeLabel(type) {
    const labels = {
        'cultural': '🏛️ 文化历史',
        'natural': '🌊 自然风光',
        'food': '🍜 美食体验',
        'leisure': '🎪 休闲娱乐'
    };
    return labels[type] || '🎯 综合';
}

function filterRoutes() {
    const typeFilter = document.getElementById('typeFilter').value;
    const durationFilter = document.getElementById('durationFilter').value;
    
    currentRoutes = favoriteRoutes.filter(route => {
        const typeMatch = typeFilter === 'all' || route.type === typeFilter;
        const durationMatch = durationFilter === 'all' || 
            (durationFilter === 'half-day' && route.duration.includes('半天')) ||
            (durationFilter === 'one-day' && route.duration === '一天') ||
            (durationFilter === 'multi-day' && !route.duration.includes('半天') && !route.duration.includes('一天'));
        
        return typeMatch && durationMatch;
    });
    
    updateStats();
    renderRoutes();
}

function sortRoutes() {
    const sortBy = document.getElementById('sortFilter').value;
    
    currentRoutes.sort((a, b) => {
        switch (sortBy) {
            case 'newest':
                return new Date(b.collectTime) - new Date(a.collectTime);
            case 'oldest':
                return new Date(a.collectTime) - new Date(b.collectTime);
            case 'duration':
                const aDuration = a.duration.includes('半天') ? 0.5 : parseInt(a.duration) || 1;
                const bDuration = b.duration.includes('半天') ? 0.5 : parseInt(b.duration) || 1;
                return bDuration - aDuration;
            case 'rating':
                return b.rating - a.rating;
            default:
                return 0;
        }
    });
    
    renderRoutes();
}

function viewRouteDetails(routeId) {
    selectedRoute = favoriteRoutes.find(route => route.id === routeId);
    if (!selectedRoute) return;
    
    const modal = document.getElementById('routeModal');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    
    modalTitle.textContent = selectedRoute.title;
    modalBody.innerHTML = `
        <div style="padding: 2rem; color: #fff;">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 2rem; margin-bottom: 2rem;">
                <div class="detail-card">
                    <h4 style="color: #00ffff; margin-bottom: 1rem;">📊 基本信息</h4>
                    <p><strong>类型：</strong>${getTypeLabel(selectedRoute.type)}</p>
                    <p><strong>时长：</strong>${selectedRoute.duration}</p>
                    <p><strong>难度：</strong>${selectedRoute.difficulty}</p>
                    <p><strong>评分：</strong>⭐ ${selectedRoute.rating}</p>
                    <p><strong>预算：</strong>${selectedRoute.estimatedCost}</p>
                </div>
                
                <div class="detail-card">
                    <h4 style="color: #00ffff; margin-bottom: 1rem;">🕒 时间信息</h4>
                    <p><strong>收藏时间：</strong>${selectedRoute.collectTime}</p>
                    <p><strong>最佳时间：</strong>${selectedRoute.bestTime}</p>
                    <p><strong>建议时长：</strong>${selectedRoute.duration}</p>
                </div>
            </div>
            
            <div class="detail-card" style="margin-bottom: 2rem;">
                <h4 style="color: #00ffff; margin-bottom: 1rem;">📝 路线描述</h4>
                <p style="line-height: 1.6;">${selectedRoute.description}</p>
            </div>
            
            <div class="detail-card" style="margin-bottom: 2rem;">
                <h4 style="color: #00ffff; margin-bottom: 1rem;">📍 包含景点 (${selectedRoute.spots.length}个)</h4>
                <div style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
                    ${selectedRoute.spots.map(spot => `<span class="spot-tag">${spot}</span>`).join('')}
                </div>
            </div>
            
            <div class="detail-card">
                <h4 style="color: #00ffff; margin-bottom: 1rem;">💡 贴心提示</h4>
                <p style="background: rgba(255, 255, 0, 0.1); padding: 1rem; border-radius: 8px; border-left: 4px solid #ffeb3b;">
                    ${selectedRoute.tips}
                </p>
            </div>
        </div>
    `;
    
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function closeRouteModal() {
    document.getElementById('routeModal').style.display = 'none';
    document.body.style.overflow = 'auto';
    selectedRoute = null;
}

function startRoute() {
    if (selectedRoute) {
        alert(`🚀 即将开始"${selectedRoute.title}"的旅程！\n\n准备好探索这些精彩景点了吗？`);
        closeRouteModal();
        // 这里可以跳转到具体的路线导航页面
        // window.location.href = `route-navigation.html?id=${selectedRoute.id}`;
    }
}

function removeFromFavorites() {
    if (selectedRoute && confirm(`确定要取消收藏"${selectedRoute.title}"吗？`)) {
        const index = favoriteRoutes.findIndex(route => route.id === selectedRoute.id);
        if (index !== -1) {
            favoriteRoutes.splice(index, 1);
            currentRoutes = [...favoriteRoutes];
            
            // 更新本地存储
            updateLocalStorage();
            
            updateStats();
            renderRoutes();
            closeRouteModal();
            
            showNotification('✅ 已取消收藏该路线');
        }
    }
}

function removeRoute(routeId) {
    const route = favoriteRoutes.find(r => r.id === routeId);
    if (route && confirm(`确定要取消收藏"${route.title}"吗？`)) {
        const index = favoriteRoutes.findIndex(r => r.id === routeId);
        if (index !== -1) {
            favoriteRoutes.splice(index, 1);
            currentRoutes = [...favoriteRoutes];
            
            // 更新本地存储
            updateLocalStorage();
            
            updateStats();
            renderRoutes();
            
            showNotification('✅ 已取消收藏该路线');
        }
    }
}

function updateLocalStorage() {
    try {
        // 只保存用户自定义添加的路线（ID大于1000的）
        const userRoutes = favoriteRoutes.filter(route => route.id > 1000);
        localStorage.setItem('favoriteRoutes', JSON.stringify(userRoutes));
    } catch (error) {
        console.error('更新本地存储失败:', error);
    }
}

function showNotification(message) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: linear-gradient(135deg, #00ffff, #0080ff);
        color: white;
        padding: 1rem 2rem;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 255, 255, 0.3);
        z-index: 10000;
        animation: slideIn 0.3s ease;
    `;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
    
    .detail-card {
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(0, 255, 255, 0.2);
        border-radius: 10px;
        padding: 1.5rem;
    }
    
    .detail-card h4 {
        margin: 0 0 1rem 0;
        font-size: 1.1rem;
    }
    
    .detail-card p {
        margin: 0.5rem 0;
        color: #ccc;
    }
    
    .detail-card strong {
        color: #fff;
    }
`;
document.head.appendChild(style);
